<template>
	<view class="page_content">
		<view class="head_content">
			<CustomNavbar :title="$t('register.title')"></CustomNavbar>
		</view>
		<view class="main_content">
			<view class="logo">
				<image class="image" :src="config.system.company" mode="widthFix"></image>
			</view>
			<view class="input_box">
				<u-form ref="uForm" :model="form" :rules="rules">
					<u-form-item prop="mobile">
						<view class="input">
							<u-input v-model="form.username" type="text" clearable :placeholder="$t('register.enterEmail')"></u-input>
						</view>
					</u-form-item>
					<!-- <u-form-item prop="code">
						<view class="input">
							<u-input v-model="form.code" type="number" clearable :placeholder="$t('login.enterCode')">
								<template slot="suffix">
									<u-code ref="uCode" uniqueKey="register-code" :keepRunning="true" @change="codeChange" seconds="60" :changeText="$t('login.resendCode')"></u-code>
									<view class="codebtn" @click="getCode">{{ login.codeTips || $t('login.getCode') }}</view>
								</template>
							</u-input>
						</view>
					</u-form-item> -->
					<u-form-item prop="registerPassword">
						<view class="input">
							<u-input v-model="form.registerPassword" type="password" clearable :placeholder="$t('register.enterPassword')"></u-input>
						</view>
					</u-form-item>
					<u-form-item prop="againPassword">
						<view class="input">
							<u-input v-model="form.againPassword" type="password" clearable :placeholder="$t('register.enterPasswordAgain')"></u-input>
						</view>
					</u-form-item>
				</u-form>
			</view>
			<view class="button_box">
				<u-button :text="$t('register.submit')" :loading="buttonLoading" :customStyle="buttonStyle" @click="submitHandle" />
			</view>
			<view class="check_box">
				<u-checkbox-group v-model="checkedList" @change="labelChange">
					<u-checkbox :name="true" :label="$t('login.readAndAgree')" labelSize="28rpx" labelColor="#333"></u-checkbox>
				</u-checkbox-group>
				<text class="text">{{ $t('register.serviceAgreement') }}</text>
				<text>{{ $t('login.and') }}</text>
				<text class="text">{{ $t('register.privacyAgreement') }}</text>
			</view>
			<view class="text_info">
				<text class="text" @click="redirectPath">{{ $t('register.haveAccount') }}{{ $t('register.goLogin') }}</text>
			</view>
		</view>
	</view>
</template>

<script>
	import { mapState, mapGetters, mapMutations, mapActions } from "vuex"
	export default {
		data() {
			return {
				buttonStyle: {
					width: '100%',
					height: '100rpx',
					border: 'none',
					fontSize: '28rpx',
					color: '#fff',
					background: 'linear-gradient(90deg, #2A82E4, #D269FF)',
					borderRadius: '20rpx',
					margin: '0',
					fontWeight: 'bold'
				},
				buttonLoading: false,
				login: {
					codeTips: '', // 验证码提示文字
					checked: true, // 协议勾选
					platform: this.$utils.platforms(), // 平台(H5 / wxMiniProgram / wxOfficialAccount)
				},
				checkedList: [true],
				form: {
					username: '',
					code: '',
					registerPassword: '',
					againPassword: '',
				},
				rules: {}
			}
		},
		created() {
			this.initializeI18nTexts()
			this.rules = this.buildRules()
		},
		computed: {
			...mapGetters('app', ['config', "share"]),
			currentLocale() {
				return this.$i18n?.locale || this.$locale.get()
			}
		},
		watch: {
			currentLocale() {
				this.login.codeTips = ''
				this.rules = this.buildRules()
				this.applyRules()
			}
		},
		onLoad() {
			
		},
		onReady() {
			this.applyRules()
		},
		methods: {
			initializeI18nTexts() {
				this.login.codeTips = ''
			},
			buildRules() {
				return {
					username: [
						{ required: true, message: this.$t('register.enterEmail'), trigger: ['blur', 'change'] },
						{ min: 6, max: 50, message: this.$t('register.emailInvalid'), trigger: ['blur', 'change'] }
					],
					registerPassword: [
						{ required: true, message: this.$t('register.enterPassword'), trigger: ['blur', 'change'] },
						{ min: 6, max: 20, message: this.$t('register.passwordInvalid'), trigger: ['blur', 'change'] }
					],
					againPassword: [
						{ required: true, message: this.$t('register.enterPasswordAgain'), trigger: ['blur', 'change'] },
						{
							validator: (rule, value, callback) => {
								if (!value) {
									callback()
									return
								}
								if (value !== this.form.registerPassword) {
									callback(this.$t('register.passwordMismatch'))
								} else {
									callback()
								}
							},
							trigger: ['change', 'blur'],
						}
					]
				}
			},
			applyRules() {
				this.$nextTick(() => {
					this.$refs.uForm && this.$refs.uForm.setRules(this.rules)
				})
			},
			...mapActions('user', ['getUserInfo']),
			submitHandle() {
				if(!this.login.checked) {
					this.$u.toast(this.$t('login.pleaseAgree'))
					return
				}
				this.$refs.uForm.validate().then(res => {
				const obj = {
						username: this.form.username,
						code: this.form.code,
						password: this.form.againPassword,
						platform: this.login.platform,
					spm: this.share.spm || ''
					}
				// 携带渠道码（若存在）
				const channel = this.$store.state.app.channel
				if (channel) {
					obj.channel = channel
					//如果存在渠道码，则清除spm
					obj.spm = ''
					this.share.spm = ''
				}
					this.registerAccount(obj)
				}).catch(err => {
					console.log(err, 'validate failed');
				})
			},
			// 1.注册账号
			registerAccount(obj) {
				this.$request('login.register', obj).then(res => {
					if(res.code === 1) {
						this.$u.toast(this.$t('register.success'))
						this.getUserInfo(res.data.token)
						this.redirectPath(2)
					}
				})
			},
			// 重定向页面
			redirectPath(count = 1) {
				const page = getCurrentPages()[0];
				if(page.route.indexOf('pages/login/register') == -1) {
					uni.navigateBack({
						delta: Number(count)
					})
				} else {
					uni.switchTab({
						url: '/pages/home/index'
					});
				}
			},
			labelChange(detail) {
				this.login.checked = detail[0] ? detail[0] : false
			},
			codeChange(text) {
				this.login.codeTips = text;
			},
			getCode() {
				if(!this.form.mobile) {
					this.$u.toast(this.$t('login.enterMobile'))
					return
				}
				let obj = {
					mobile: this.form.mobile,
					event: 'register'
				}
				if (this.$refs.uCode.canGetCode) {
					uni.showLoading({
						title: this.$t('login.gettingCode')
					})
					this.$request('login.sendCode', obj, false).then(res => {
						if(res.code === 1) {
							uni.hideLoading();
							uni.$u.toast(this.$t('login.codeSent'));
							this.$refs.uCode.start();
						} else {
							uni.hideLoading();
							uni.$u.toast(res.msg);
						}
					}).catch(err => {
						uni.hideLoading();
						uni.$u.toast(this.$t('login.codeSendFailed'));
					})
				} else {
					uni.$u.toast(this.$t('login.waitCountdown'));
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.main_content {
		padding: 60rpx;
		overflow-y: auto;
		
		.logo {
			width: 100%;
			padding: 40rpx 100rpx 100rpx 100rpx;
			
			.image {
				width: 100%;
			}
		}
		
		.input_box {
			::v-deep .u-form {
				.u-form-item__body {
					padding: 0 0 40rpx 0 !important;
				}
				
				.u-form-item__body__right__message {
					margin-left: 0 !important;
					line-height: 1.5em;
					font-size: 28rpx;
					padding: 0 10rpx 20rpx 10rpx;
				}
			}
			
			.input {
				width: 100%;
				
				::v-deep .u-input {
					height: 100rpx;
					background: #F7F8F9;
					border-radius: 16rpx;
					border: none;
					padding: 12rpx 24rpx !important;
				}
				
				.codebtn {
					font-size: 28rpx;
					color: #333;
				}
			}
		}
		
		.button_box {
			margin: 40rpx 0;
		}
		
		.check_box {
			display: flex;
			align-items: center;
			font-size: 28rpx;
			
			.text {
				color: #583EF2;
			}
		}
		
		.text_info {
			margin-top: 60rpx;
			text-align: center;
			
			.text {
				color: #626262;
				font-size: 28rpx;
			}
		}
	}
</style>
